from django.shortcuts import render
import json,re,random,io,sys,requests,time

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
# Create py2neo connection
graph = Graph(host='localhost',auth=('neo4j','123'))
# Create your views here.


# //跨域问题
@csrf_exempt
def initAll(request):
    # 全局变量
    global graph
    num = eval(request.body.decode()).get('num')
    sql = "MATCH (from:Country) -[r] -> (to:Country) RETURN from,r,to limit "+ str(num);
    nodes_source = graph.run(sql).data()
    return JsonResponse({"status": "ok","success":True,"data":nodes_source})

@csrf_exempt
def commonSearch(request):
    # 全局变量
    global graph
    f = eval(request.body.decode()).get('from')
    r = eval(request.body.decode()).get('r')
    to = eval(request.body.decode()).get('to')
    if r == 'all':
        sql = "MATCH (from:Country) <- [r] -> (to:Country) where from.Note =~'.*"+f+".*' and to.Note =~'.*"+to+".*'  RETURN from,r,to";
    elif r == 'Emigrants':
        sql = "MATCH (from:Country) - [r] -> (to:Country) where from.Note =~'.*" + f + ".*' and r.type='Emigrants' and to.Note =~'.*" + to + ".*'  RETURN from,r,to";
    elif r == 'Immigrants':
        sql = "MATCH (from:Country) - [r] -> (to:Country) where from.Note =~'.*" + f + ".*' and r.type='Immigrants' and to.Note =~'.*" + to + ".*'  RETURN from,r,to";
    nodes_source = graph.run(sql).data()
    return JsonResponse({"status": "ok","success":True,"data":nodes_source})

@csrf_exempt
def login(request):
    # 全局变量
    global graph
    username = eval(request.body.decode()).get('username')
    password = eval(request.body.decode()).get('password')
    if username == 'admin' and password == '123':
        return JsonResponse({"status": "ok","success":True})
    else:
        return JsonResponse({"status": "ok","success":False})